package com.test.thread;

import java.util.Random;

import org.apache.log4j.Logger;

public class MyThread extends Thread {

	static final Logger log = Logger.getLogger(MyThread.class);

	private boolean done = true;

	private int taskId;

	public MyThread(String id) {
		super("MyThread#" + id);
	}

	public void run() {
		while (true) {
			System.out.println(this + " is running...");
			if (done) {
				try {
					log.info(this + " ,No job,I am waiting...");
					synchronized (this) {
						wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					log.error("wait exception:", e);
				}
			}
			done = false;
			doTask();
			done = true;
			log.info(this + " is finished.");
		}
	}

	private void doTask() {
		Random r = new Random();
		int w = r.nextInt(500) + 700;
		try {
			Thread.sleep(w);
		} catch (InterruptedException e) {
			e.printStackTrace();
			log.error("doTask sleep exception:", e);
		}
		log.info(this + " is doing task: " + this.taskId + ", waiting time:" + w);
		if (w > 1190 && this.getName().equals("MyThread#02")) {
			log.error(this.getName() + " will exit.");
			throw new RuntimeException("Stopping the thread:" + this.getName());
		}

	}

	public String toString() {
		return "#" + this.getName();
	}

	public boolean isDone() {
		return done;
	}

	public void setTaskId(int id) {
		this.taskId = id;
	}

}
